"""
对话会话模型
"""
from sqlalchemy import Column, String, Integer, ForeignKey, Text, Enum as SQLEnum
from sqlalchemy.orm import relationship
import enum

from app.models.base import BaseModel


class ConversationStatus(str, enum.Enum):
    """对话状态枚举"""
    ACTIVE = "active"           # 进行中
    COMPLETED = "completed"     # 已完成
    TRANSFERRED = "transferred" # 已转人工
    CLOSED = "closed"          # 已关闭


class Conversation(BaseModel):
    """对话会话模型"""
    
    __tablename__ = "conversations"
    
    # 关联用户
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True, comment="用户ID")
    
    # 会话信息
    session_id = Column(String(100), unique=True, index=True, nullable=False, comment="会话ID")
    title = Column(String(200), nullable=True, comment="对话标题")
    status = Column(
        SQLEnum(ConversationStatus),
        default=ConversationStatus.ACTIVE,
        nullable=False,
        comment="对话状态"
    )
    
    # 统计信息
    message_count = Column(Integer, default=0, comment="消息数量")
    
    # 上下文摘要（用于长对话）
    summary = Column(Text, nullable=True, comment="对话摘要")
    
    # 评价信息
    rating = Column(Integer, nullable=True, comment="用户评分(1-5)")
    feedback = Column(Text, nullable=True, comment="用户反馈")
    
    # 关系
    user = relationship("User", back_populates="conversations")
    messages = relationship(
        "Message",
        back_populates="conversation",
        cascade="all, delete-orphan",
        order_by="Message.id"
    )
    
    def __repr__(self):
        return f"<Conversation(id={self.id}, session_id={self.session_id}, status={self.status})>"
    
    @property
    def is_active(self) -> bool:
        """是否活跃"""
        return self.status == ConversationStatus.ACTIVE

